#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "net.h"
#include <unistd.h>

static int backlog = 50;
struct sockaddr_in socket_addr;
struct sockaddr_in client_addr;
socklen_t addrlen = sizeof(client_addr);
char client_ip[20] = "";

static int max_data_len = 556; //bytes

int net_init(u32 ip_addr, u32 port) {
    int ret = 0;
    int server_socket = -1;
    DBG("net init start\n");

    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("server socket build error:\n");
        return -1;
    }

    socket_addr.sin_family = AF_INET;
    socket_addr.sin_addr.s_addr = htonl(ip_addr);
    socket_addr.sin_port = htons(port);
    ret = bind(server_socket, (struct sockaddr *)&socket_addr, sizeof(socket_addr));
    if (ret == -1) {
        perror("server socket bind error:\n");
        close(server_socket);
        return -1;
    }

    ret = listen(server_socket, backlog);
    if (ret == -1) {
        perror("server socket listen error:\n");
        close(server_socket);
        return -1;
    }

    return server_socket;
}

int net_recive(int sockfd,void *buff) {
    return recv(sockfd, buff, max_data_len, 0);
}

int net_send(int sockfd, void *buff, int size) {
    return send(sockfd, buff, size, 0);
}

int net_accept(int server_socket) {
    int client_socket = -1;
    client_socket = accept(server_socket, (struct sockaddr*) &client_addr, &addrlen);
    if (client_socket == -1) {
        perror("accept error:\n");
        return -1;
    }

    DBG("client connet !\n");
    inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, client_ip, sizeof(client_ip));
    DBG("client IP addr: %s\n", client_ip);
    DBG("client port: %d\n", client_addr.sin_port);
    return client_socket;
}